import React, { PureComponent } from 'react';
import { Form, Select, Input, Button, Upload, Icon, Card } from 'antd';
import { connect } from 'dva';
import PageHeaderLayout from '../../layouts/PageHeaderLayout'; //引入面包屑
const Option = Select.Option;
@connect(({ category }) => ({
  category,
}))
class Up extends PureComponent {
  state = {
    loading: false,
    file_name: '',
  };
  //获取下拉列表--图片类型
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'category/cate',
    });
  }
  //图片转码 base64
  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  //用来判断图片有没有上传成功的
  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      this.setState({
        loading: false,
      });
    }
  };
  //上传前的工作
  beforeUpload(file) {
    this.getBase64(file, imageUrl => {
      this.setState({
        imageUrl,
        loading: false,
      });
      if (imageUrl) {
        let apirul = 'http://localhost:3000/pic_url';
        let u = imageUrl.substring(imageUrl.indexOf(',') + 1, imageUrl.length);
        let data = {
          image_name: file.name,
          image_data: u,
        };
        console.log(data);
        fetch(apirul, {
          method: 'post',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        })
          .then(res => res.json())
          .then(res => {
            this.setState({ pic_url: res.pic_url });
          });
      }
    });
    return 1;
  }
  //提交表单数据
  handleSubmit = e => {
    let apirul = 'http://localhost:3000/picinfor';
    //接口地址
    let data = {
      name: this.props.form.getFieldsValue().name,
      category: this.props.form.getFieldsValue().category,
      pic_url: this.state.pic_url,
    };
    fetch(apirul, {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then(function(res) {
        return res.json();
      })
      .then(res => {
        console.log(res);
      });
  };

  render() {
    const { category: { cate } } = this.props;
    const Option = Select.Option;
    const FormItem = Form.Item;
    //上传图片的base64编码
    const imageUrl = this.state.imageUrl;
    //获取表单输入值的方法
    const { getFieldProps } = this.props.form;
    //表单项栅格设置
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    //下拉列表项
    const children = [];
    for (let i = 0; i < cate.length; i++) {
      children.push(
        <Option key={i} value={cate[i].category_name}>
          {cate[i].category_name}
        </Option>
      );
    }
    //上传图片按钮
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <PageHeaderLayout title="图片添加" content="图片添加用于向用户收集人员相片信息。">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit}>
            <FormItem {...formItemLayout} label="图片名称">
              <Input {...getFieldProps('name')} style={{ width: '300px' }} />
            </FormItem>

            <FormItem {...formItemLayout} label="图片类型">
              <Select {...getFieldProps('cate')} style={{ width: '300px' }}>
                {/*{  {children}  }此处注释，可以用 上面的for循环children = []，但要加key下面直接用map循环 */}
                {cate.map(function(name, key) {
                  return <option key={key}>{name}</option>;
                })}
              </Select>
            </FormItem>

            <FormItem {...formItemLayout} label="上传图片">
              <Upload
                {...getFieldProps('pic_url')}
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action=""
                beforeUpload={this.beforeUpload.bind(this)}
                onChange={this.handleChange}
              >
                {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
              </Upload>
            </FormItem>

            <FormItem wrapperCol={{ span: 12, offset: 6 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
//Form.create()方法是将this.props.form填进来，使能获取用户输入的值
const UpForm = Form.create()(Up);
export default UpForm;
